package org.example.backend.demos.web.config;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import jakarta.annotation.PreDestroy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import lombok.Data;
@Configuration
@Data
public class CosConfig {

    private TransferManager transferManager;
    private COSClient cosClient;

    @Bean
    public COSClient cosClient() {
        // 确保正确创建并返回 COSClient 实例
        // 获取系统变量的密钥，这里不方便公开
        String secretId = System.getenv("TENCENT_COS_SECRET_ID");//用户的 SecretId，
        String secretKey = System.getenv("TENCENT_COS_SECRET_KEY");//用户的 SecretKey，
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 客户端设置：
        ClientConfig clientConfig = new ClientConfig();
        // 设置地域
        clientConfig.setRegion(new Region("ap-nanjing"));
        // 生成客户端
        COSClient cosClient = new COSClient(cred, clientConfig);

        return cosClient; // 调用创建客户端的方法
    }

    // 创建 TransferManager 实例，这个实例用来后续调用高级接口
    @Bean
    public TransferManager createTransferManager(COSClient cosClient) {
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        return transferManager;
    }

    @PreDestroy
    public void shutdown() {
        if (transferManager != null) {
            transferManager.shutdownNow();
        }
        if (cosClient != null) {
            cosClient.shutdown();
        }
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    @ResponseStatus(HttpStatus.PAYLOAD_TOO_LARGE)
    public String handleMaxSizeException(MaxUploadSizeExceededException exc) {
        return "文件大小超出限制";
    }

}
